import React from 'react';
import {connect} from 'dva'
import styles from './style/index.less';

import router from 'umi/router';
import { WhiteSpace, InputItem, Toast, Button, Icon } from 'antd-mobile';

import { routerFormat } from 'utils'

@connect(({login}) => ({...login}))
class Login extends React.Component {
  state = {
    hasError: false,
    pwdError: false,
    username: '',
    password: '',
    loading: false,
    isChecked: true,
  }

  // 记住密码
  handleCheck = (e) => {
    e.preventDefault();
    const { isChecked } = this.state;
    this.setState({ isChecked: !isChecked })
  }
  // 用户名
  onErrorClick = () => {
    if (this.state.hasError) {
      Toast.info('请输入用户名！');
    }
  }
  onChange = (username) => {
    if (username.replace(/\s/g, '').length < 1) {
      this.setState({
        hasError: true,
      });
      this.inputRef.focus();
    } else {
      this.setState({
        hasError: false,
      });
    }
    this.setState({
      username,
    });
  }
  // 密码
  onPwdErrorClick = () => {
    if (this.state.hasError) {
      Toast.info('请输入密码！');
    }
  }
  onPwdChange = (password) => {
    if (password.replace(/\s/g, '').length < 1) {
      this.setState({
        pwdError: true,
      });
      this.inputPwdRef.focus();
    } else {
      this.setState({
        pwdError: false,
      });
    }
    this.setState({
      password,
    });
  }

  // 发送请求
  query = async() => {
    const { username, password } = this.state;

    this.setState({ loading: true });
    await this.props.dispatch({
      type: 'login/queryUserInfo',
      payload: {
        username,
        password,
        sys: 'app',
      }
    })
    .then((data) => {
      const { isSuccess, user, msg } = data;
      if(isSuccess === true){
        Toast.success('登录成功，页面正在跳转...', 3, () => {
          const { user: userInfo, menus } = data;
          localStorage.setItem('userInfo', JSON.stringify(userInfo))
          // 处理路由信息
          const nowRouteList = routerFormat(menus);
          localStorage.setItem('routeList', JSON.stringify(nowRouteList))

          localStorage.setItem('isInit', JSON.stringify(true))
          router.push({ pathname: '/' })
        });
      }else{
        Toast.fail(msg ? msg : '登录失败');
      }
      this.setState({ loading: false });
    });
  }

  handleClick = async() => {
    const { username, password, hasError, pwdError } = this.state;
    if (username.length<1 || password.lenght < 1 || hasError || pwdError) {
      Toast.info('用户名或密码不能为空！'); return;
    }
    await this.query()
  }


  render() {
    const { loading, isChecked } = this.state;
    const checkCls = isChecked === true ? styles.actived : '';

    return (<div className={styles.Login}>
      <div className={styles.inner}>
        <InputItem
          type="text"
          placeholder="用户名"
          clear
          error={this.state.hasError}
          onErrorClick={this.onErrorClick}
          onChange={this.onChange}
          value={this.state.username}
          ref={el => this.inputRef = el}
        />
        <WhiteSpace size="lg" />
        <InputItem
          type="password"
          placeholder="密码"
          clear
          error={this.state.pwdError}
          onErrorClick={this.onPwdErrorClick}
          onChange={this.onPwdChange}
          value={this.state.password}
          ref={el => this.inputPwdRef = el}
        />
        <WhiteSpace size="lg" />

        <label className={`${styles.check} ${checkCls}`} onClick={this.handleCheck}>
          <span><Icon type={'check'} size={'xxs'} style={{ verticalAlign: 'top' }}/></span>记住密码
        </label>
        <WhiteSpace size="lg" />
        <Button type="primary" style={{backgroundColor: '#3a68ff'}}
          onClick={this.handleClick}
          loading={loading}
        >立即登录</Button>
      </div>
    </div>)
  }
}

export default Login;
